<?php
declare (strict_types = 1);

namespace app\controller\admin;

use app\common\service\redis\PoolRedis;
use app\model\AdminStaffPhonePool;
use app\util\ExcelHandle;
use app\util\ReturnCode;
use think\facade\Queue;
use think\facade\Request;
use think\facade\Validate;
use think\Response;

class PhonePool extends Base {

    /**
     * 显示手机池列表
     *
     * @return \think\Response
     */
    public function index(): Response
    {
        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $school_id = $this->request->get('school_id', $this->userInfo['school_id']);
        $start = $this->request->get('page', 1);
        $phone = $this->request->get('phone', '');

        $where = [];
        $obj = (new AdminStaffPhonePool());

        if ($phone) {
            array_push($where, ['phone', 'like', "%{$phone}%"]);
        }
        if ($school_id > 0) {
            array_push($where, ['school_id', '=', $school_id]);
        }

        $listObj = $obj->where($where)->with(['school'])
            ->paginate(['page' => $start, 'list_rows' => $limit])->toArray();

        return $this->buildSuccess([
            'list'  => $listObj['data'],
            'count' => $listObj['total']
        ]);

    }

    /**
     * 保存手机池
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function add(): Response
    {
        $data = Request::only(['phone','uid'], 'post');
        $validate = Validate::rule([
            'phone|-手机号'=>'require',
            'uid|UID'=>'require'
        ]);
        if (!$validate->check($data)) {
            return $this->buildFailed(ReturnCode::PARAM_INVALID, $validate->getError());
        }

        $res = AdminStaffPhonePool::create([
            'school_id' => $this->request->post('school_id', ''),
            'phone' => $this->request->post('phone', ''),
            'uid' => $this->request->post('uid','')
        ]);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR);
        }

        return $this->buildSuccess();
    }


    /**
     * 编辑手机池
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit(): Response
    {
        $data = Request::only(['phone','uid'], 'post');
        $validate = Validate::rule([
            'phone|-手机号'=>'require',
            'uid|UID'=>'require'
        ]);
        if (!$validate->check($data)) {
            return $this->buildFailed(ReturnCode::PARAM_INVALID, $validate->getError());
        }

        $res = AdminStaffPhonePool::update([
            'id' => $this->request->post('id', 0),
            'school_id' => $this->request->post('school_id', ''),
            'phone' => $this->request->post('phone', ''),
            'uid' => $this->request->post('uid','')
        ]);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR);
        }

        return $this->buildSuccess();
    }


    /**
     * 删除指定手机池
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function del(): Response
    {
        $id = $this->request->get('id');
        if (!$id) {
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }
        AdminStaffPhonePool::destroy($id);

        return $this->buildSuccess();
    }

    public function upload(): Response {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('excel_file');
        $school_id = request()->post('school_id');
        // 上传到本地服务器
        try {
            validate(['image'=>'fileSize:20480|fileExt:xls,xlsx'])
                ->check([$file]);
            $fileExtendName = substr(strrchr($file->getOriginalName(), '.'), 1);
            $filePath = $file->getPathname();
            if (is_file($filePath)){
                $cols = [['1' => 'number'],['2' =>'phone'],['3'=>'uid']];
                $data = ExcelHandle::importExcel($filePath,$cols,$fileExtendName);

                $redis = PoolRedis::instance();
                $redis->multi(\Redis::PIPELINE);
                foreach ($data as $datum) {
                    $datum['school_id'] = $school_id;
                    $redis->lPush("upload_phone_pool", serialize($datum));
                }
                $redis->exec();
                Queue::push('app\task\job\UploadSyncHandlerJob@fire', [
                    'model'=> AdminStaffPhonePool::class,
                    'action' => 'upload_phone_pool'
                ]);
            }
            return $this->buildSuccess();
        } catch (\think\exception\ValidateException $e) {
            return $this->buildFailed(ReturnCode::FILE_SAVE_ERROR, $e->getMessage());
        }
    }


    /**
     * @func download
     * @desc 导出文件
     * @return \think\Response
     * @Time: 2021/12/17 11:18
     */
    public function download(): Response  {
        $titles = [['id' => '序号'],['phone' => '手机号'],['uid'=>'UID']];

        $phone = $this->request->get('phone', '');
//        $captcha = $this->request->get('captcha', '');
//        $status = $this->request->get('status', 0);

        try {
            $where = [];

            $obj = (new AdminStaffPhonePool());

            if ($phone) {
                array_push($where, ['phone', 'like', "%{$phone}%"]);
            }
//            if ($captcha) {
//                array_push($where, ['captcha', 'like', "%{$captcha}%"]);
//            }
//            if ($status) {
//                array_push($where, ['status', '=', "{$status}"]);
//            }

            $listObj = $obj->where($where)
                ->field('id,phone,uid')
                ->select()->toArray();
            $exportData = [];
            $len = 1;
            foreach ($listObj as $datum) {
                $newItem = array_merge(['id' => $len],$datum);
                array_push($exportData, $newItem);
                $len++;
            }
            ExcelHandle::downLoadExcel('手机号池' . date('YmdHi'), $titles, $exportData);

        } catch (\think\exception\ValidateException $e) {
            return $this->buildFailed(ReturnCode::FILE_SAVE_ERROR, $e->getMessage());
        }
    }

}
